package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //String remoteAddr = request.getRemoteAddr();
        //if (remoteAddr.startsWith("192")){
          //  response.sendRedirect("http://www.64365.com/tuwen/ciumu/");
            //return;
        //}

        String requestURI = request.getRequestURI();
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };

        boolean flag = cheak(requestURI, urls);

        if (flag){
            chain.doFilter(request, response);
            return;
        }

        Long employee = (Long) request.getSession().getAttribute("employee");

        if (employee != null){
            //6.把用户id保存在线程域中，方便公共字段进行取用
            BaseContext.setThreadLocal(employee);
            chain.doFilter(request, response);
            return;
        }
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            BaseContext.setThreadLocal(userId);
            chain.doFilter(request, response);
            return;
        }


        log.info("用户未登录");
        String s = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().print(s);
        return;
    }



    private boolean cheak(String requestURI, String[] urls) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
